<template>
    <el-dialog v-model="outerVisible" title="新增公告" @close="closeAddShop" width="30%" :close-on-click-modal="false">
        <template #default>
            <el-dialog v-model="innerVisible" width="30%" :title="showInfo" append-to-body />
        </template>
        <template #footer>
            <el-form ref="typeFormRef" :model="typeForm" :rules="rules" label-width="120px" class="demo-typeForm"
                :size="formSize" status-icon>
                <el-form-item label="标题" prop="title">
                    <el-input v-model="typeForm.title" style="width: 180px" />
                </el-form-item>
                <el-form-item label="内容" prop="content">
                    <el-input v-model="typeForm.content" style="width: 180px" />
                </el-form-item>
                <el-form-item label="图片" prop="path">
                    <el-upload 
                        ref="upload"
                        class="avatar-uploader"
                        action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                        :show-file-list="false"
                        :on-change="handleFileChange"
                        :auto-upload="false">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm(typeFormRef)"
                        :loading="addShopLoading">添加公告</el-button>
                    <el-button @click="resetForm(typeFormRef)">清空</el-button>
                </el-form-item>
            </el-form>
        </template>
    </el-dialog>
</template>
  
<script lang="ts" setup>
import { ref, toRefs, toRef, reactive, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules} from 'element-plus'
import type { UploadInstance,UploadFile,UploadFiles } from 'element-plus';
import { Plus } from '@element-plus/icons-vue'
import { addAnn } from '@/apis/announcement'
import type { UploadProps } from 'element-plus'



const formSize = ref('default')
const typeFormRef = ref<FormInstance>()

const props = defineProps({
    addShow: Boolean,
    types: Object
})

const typeForm = reactive({
    title:'',
    content: '',
})

const showInfo = ref('')

const rules = reactive<FormRules>({
    title: [
        { required: true, message: '请输入标题', trigger: 'blur' },
        { min: 1, max: 10, message: '编号长度在1到10个字符', trigger: 'blur' },
    ],
    content: [
        { required: true, message: '请输入内容', trigger: 'blur' },
        { min: 2, max: 100, message: '名称长度在2到100个字符', trigger: 'blur' },
    ]
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            // console.log('submit!')
            submitAdd();
        } else {
            console.log('error submit!', fields)
        }
    })
}
const emit = defineEmits(['closeAddShop', 'addShopComplete'])

const addShopLoading = ref(false);


//添加商品
const submitAdd = async () => {
    console.log("file",files.value)
    console.log("typeForm",typeForm);
    
    let formData = new FormData();
    formData.append('file',files.value)
    formData.append('title',typeForm.title)
    formData.append('content',typeForm.content)  
    // console.log("formData",formData);     
    addShopLoading.value = true;   
    try {
        console.log(typeForm);   
        const addResult: any = await addAnn(formData);
        console.log(addResult);
        addShopLoading.value = false;
        if (addResult.success) {
            console.log("addResult", addResult)
            outerVisible.value = false;
            emit('addShopComplete');
            resetForm(typeFormRef.value)
            ElMessage({
                    type: 'info',
                    message: addResult.message,
                })
        } else {
            showInfoBox(addResult.message)
        }

    } catch (error) {
        console.log(error);
        addShopLoading.value = false;
    }
}

const showInfoBox = (info: string) => {
    showInfo.value = info;
    innerVisible.value = true;
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const outerVisible = computed({
    get() {
        return props.addShow;
    },
    set(v) {
        emit('closeAddShop', "close Add shop")
    },
});

const innerVisible = ref(false)

const closeAddShop = () => {
    console.log("close add shop")
    outerVisible.value = false;
}

const files:any = ref()

const upload = ref<UploadInstance>()

const imageUrl = ref('')

const handleFileChange = (uploadFile:UploadFile,UploadFiles:UploadFiles)=>{
    const type = ['image/png'];
    const extFileName:string = uploadFile.raw?.type as string;
    const extFileSize:Number = uploadFile.raw?.size as Number;
    console.log(uploadFile.raw)
    if(type.indexOf(extFileName)===-1){
      ElMessage({
        type:'warning',
        message:'文件类型必须是png图片文件'
      })
      upload.value!.clearFiles()
      return false;
    }else if(extFileSize >500000){
      ElMessage({
        type:'warning',
        message:'文件大小不能大于500K'
      })
      upload.value!.clearFiles()
      return false;
    }
    imageUrl.value = window.URL.createObjectURL(uploadFile.raw as Blob)//将选好的照片显示出来
    files.value = uploadFile.raw; 
    upload.value!.clearFiles()
  }

</script>
<style scoped>
.dialog-footer button:first-child {
    margin-right: 10px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>